<template>
  <div>
    <template v-if="selectModel">
      <el-tree
        ref="tree"
        :data="treeList"
        show-checkbox
        node-key="id"
        @check="getCurrentNode"
        :default-checked-keys="selectModelKeysNew"
        :props="treeProps">
      </el-tree>
    </template>
    <template v-else>
      <div class="divBox">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <div class="container">
              <el-form inline size="small">
                <!-- <el-form-item label="状态：">
                  <el-select v-model="listPram.status" placeholder="状态" class="selWidth" @change="handlerGetList">
                    <el-option label="全部" :value="-1"></el-option>
                    <el-option label="显示" :value="1"></el-option>
                    <el-option label="不显示" :value="0"></el-option>
                  </el-select>
                </el-form-item> -->
                <template v-if="false">
                  <el-form-item label="名称：">
                    <el-input v-model="listPram.name" placeholder="请输入名称" class="selWidth" size="small" clearable>
                      <!--                    <el-button slot="append" icon="el-icon-search" @click="handlerGetList" size="small"/>-->
                    </el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button icon="el-icon-search" size="mini" type="primary" @click="handlerGetList">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                  </el-form-item>
                </template>

                <el-form-item class="el-form-item-align-right">
                  <el-button icon="el-icon-circle-plus" size="mini" type="primary" @click="handleAddMenu({id:0,name:'顶层目录'})" v-hasPermi="[permissionNamePrefix+'save']">添加{{ biztype.name }}</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <el-table
            ref="treeList"
            v-loading="loading"
            :data="treeList"
            size="mini"
            class="table"
            highlight-current-row
            :expand-row-keys="isShowTableLine1"
            row-key="id"
            :tree-props="{children: 'child', hasChildren: 'hasChildren'}"
          >
            <el-table-column prop="name" label="名称" min-width="200">
              <template slot-scope="scope">
                {{ scope.row.name }} | ID:{{ scope.row.id }}
              </template>
            </el-table-column>

            <!-- 公用数据配置特有 -->
            <template v-if="!selectModel">
              <el-table-column label="排序" prop="sort" min-width="100" />
              <el-table-column
                label="状态"
                min-width="120"
              >
              <!--  -->
                <template slot-scope="scope" v-if="checkPermi([permissionNamePrefix+'update:status'])">
                  <el-switch
                    v-if="(biztype.value === 1 && scope.row.pid !== 0) /*|| biztype.value === 2*/"
                    v-model="scope.row.status"
                    :active-value="1"
                    :inactive-value="0"
                    active-text="显示"
                    inactive-text="隐藏"
                    @change="onchangeIsShow(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="195" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    v-if="scope.row.pid === 0"
                    type="text"
                    size="small"
                    @click="handleAddMenu(scope.row)"
                  >添加{{ wordText }}</el-button>
                  <el-button icon="el-icon-edit" type="primary"  size="small" @click="handleEditMenu(scope.row)" v-hasPermi="[permissionNamePrefix+'info']" :style="scope.row.pid !== 0?'margin-left:75px;':''">编辑</el-button>
                  <el-button v-if="scope.row.pid !== 0" icon="el-icon-delete" type="danger"  size="small" @click="handleDelMenu(scope.row)"  v-hasPermi="[permissionNamePrefix+'delete']">删除</el-button>
                </template>
              </el-table-column>
            </template>
          </el-table>
        </el-card>
      </div>
    </template>
    <el-dialog
      :title="(editDialogConfig.isCreate===0?`创建${biztype.name}`:`编辑${biztype.name}`)"
      :visible.sync="editDialogConfig.visible"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <edit
        v-if="editDialogConfig.visible"
        :prent="editDialogConfig.prent"
        :is-create="editDialogConfig.isCreate"
        :edit-data="editDialogConfig.data"
        :biztype="editDialogConfig.biztype"
        :all-tree-list="treeList"
        @hideEditDialog="hideEditDialog"
      />
    </el-dialog>
  </div>
</template>

<script>
import * as categoryApi from '@/api/categoryApi.js'
import info from './info'
import edit from './edit'
import * as selfUtil from '@/utils/ZBKJIutil.js'
import { checkPermi, checkRole } from "@/utils/permission";
import {categroyUpdateDepartStatus, treeDepartCategroy} from "@/api/categoryApi.js";
import {staticCategoryList, staticGuaranteeMethodList} from "@/utils/constants";
export default {
  // name: "list"
  components: {info, edit },
  props: {
    biztype: { // 类型，1 公用数据，2 求职意向
      type: Object,
      default: { value: -1 },
      validator: (obj) => {
        return obj.value > 0
      }
    },
    pid: {
      type: Number,
      default: 0,
      validator: (value) => {
        return value >= 0
      }
    },
    selectModel: { // 是否选择模式
      type: Boolean,
      default: false
    },
    selectModelKeys: {
      type: Array
    },
    rowSelect: {}
  },
  data() {
    return {
      selectModelKeysNew: this.selectModelKeys,
      loading: false,
      constants: this.$constants,
      treeProps: {
        label: 'name',
        children: 'child',
        // expandTrigger: 'hover',
        // checkStrictly: false,
        // emitPath: false
      },
      // treeCheckedKeys:[],// 选择模式下的属性结构默认选中
      multipleSelection: [],
      editDialogConfig: {
        visible: false,
        isCreate: 0, // 0=创建，1=编辑
        prent: {}, // 父级对象
        data: {},
        biztype: this.biztype // 统一主业务中的目录类型
      },
      dataList: [],
      treeList: [],
      listPram: {
        pid: this.pid,
        type: this.biztype.value,
        //status: -1,
        name: '',
        page: this.$constants.page.page,
        limit: this.$constants.page.limit[0]
      },
      viewInfoConfig: {
        data: null,
        visible: false
      },
      defaultImg:require('@/assets/imgs/moren.jpg'),
      defaultFaceUrl:require('@/assets/imgs/face_man.jpg'),
      wordText:'子目录',
      permissionNamePrefix:'',
      isShowTableLine1:[],//是否展开列表第一行，部门管理和公用数据配置都显示
    }
  },
  beforeMount() {
    if(this.biztype.value == 1){
      //公用数据配置
      //this.isShowTableLine1 = ['1']
      this.permissionNamePrefix='admin:system:category:'
    }
  },
  mounted() {
    this.handlerGetTreeList()
  },
  methods: {
    checkPermi, //权限控制
    //控制长文本显示和收起
    showMore (row, flag) {
      this.$set(row,'show',flag)
    },
    onchangeIsShow(row){
      const _pram = { id: row.id , status: row.status}
      categoryApi.categroyUpdateStatus( _pram , this.biztype.value).then(() => {
        this.$message.success('修改成功')
        this.handlerGetTreeList()
      }).catch(()=>{
        row.status = !row.status
      })
    },
    handleEditMenu(rowData) {
      this.editDialogConfig.isCreate = 1
      this.editDialogConfig.data = rowData
      this.editDialogConfig.prent = rowData
      this.editDialogConfig.visible = true
    },
    handleAddMenu(rowData) {
      this.editDialogConfig.isCreate = 0
      this.editDialogConfig.prent = rowData
      this.editDialogConfig.data = {}
      this.editDialogConfig.biztype = this.biztype
      this.editDialogConfig.visible = true
    },
    getCurrentNode(data) {
      let node = this.$refs.tree.getNode(data);
      this.childNodes(node);
      // this.parentNodes(node);
      //是否编辑的表示
      // this.ruleForm.isEditorFlag = true;
      //编辑时候使用
      this.$emit('rulesSelect', this.$refs.tree.getCheckedKeys());
      // this.selectModelKeys = this.$refs.tree.getCheckedKeys();
      //无论编辑和新增点击了就传到后台这个值
      // this.$emit('rulesSelect', this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys()));
      // this.ruleForm.menuIdsisEditor = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys());
    },
    //具体方法可以看element官网api
    childNodes(node){
      let len = node.childNodes.length;
      for(let i = 0; i < len; i++){
        node.childNodes[i].checked = node.checked;
        this.childNodes(node.childNodes[i]);
      }
    },
    parentNodes(node){
      if(node.parent){
        for(let key in node){
          if(key == "parent"){
            node[key].checked = true;
            this.parentNodes(node[key]);
          }
        }
      }
    },

    handleDelMenu(rowData) {
      this.$confirm('确定删除当前数据?').then(() => {
        if(this.biztype.value == 1){
          categoryApi.deleteCategroy(rowData).then(data => {
            this.handlerGetTreeList()
            this.$message.success('删除成功')
          })
        }
      })
    },
    handlerGetList() {
      this.handlerGetTreeList();
      // categoryApi.listCategroy({status:this.listPram.status, type: 1 }).then(data => {
      //   this.treeList = data.list
      // })
    },

    //获取列表页数据树
    handlerGetTreeList() {
      const _pram = { name: this.listPram.name }
      this.loading = true
      if(this.biztype.value == 1){
        //公用数据配置
        categoryApi.treeCategroy().then(data => {
          this.treeList = this.handleAddArrt(data)
          this.loading = false
        }).catch(()=>{
          this.loading = false
        })
      }
    },
    handlerGetInfo(id) {
      this.viewInfoConfig.data = id
      this.viewInfoConfig.visible = true
    },
    handleNodeClick(data) {
      console.log('data:', data)
    },
    handleAddArrt(treeData) {
      const _result = selfUtil.addTreeListLabel(treeData)
      return _result
    },
    hideEditDialog() {
      setTimeout(() => {
        this.editDialogConfig.prent = {}
        this.editDialogConfig.type = 0
        this.editDialogConfig.visible = false
        this.handlerGetTreeList()
      }, 200)
    },
    /*hideScanDialog() {
      setTimeout(() => {
        this.scanDialogConfig.type = 0
        this.scanDialogConfig.visible = false
        this.handlerGetTreeList()
      }, 200)
    },*/
    handleSelectionChange(d1, { checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys }) {
      // this.multipleSelection =  checkedKeys.concat(halfCheckedKeys)
      this.multipleSelection = checkedKeys
      this.$emit('rulesSelect', this.multipleSelection)
    },
    resetQuery(){
      this.listPram.name = '';
      this.handlerGetTreeList()
    }
  }
}
</script>

<style scoped lang="scss">
  ::v-deep .el-table th{
    font-weight: bold;
  }
  ::v-deep .el-card__header{
    border-bottom:0;
    padding:18px 20px 0 20px;
  }
  ::v-deep .el-card__body{
    padding:0 20px 20px 20px;
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .table .showMore{
    display:block;
    width:100%;
    word-break:keep-all;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
  }
</style>
